package com.bookkeeping.cn.util;

import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.Typeface;

import java.util.Random;

public class CaptchaGenerator {
    private static final String CHARS = "123456789ABCDEFGHJKLMNPQRSTUVWXYZ";
    private static final int CODE_LENGTH = 4;
    private static final int WIDTH = 120;
    private static final int HEIGHT = 40;
    private static final int FONT_SIZE = 30;
    private static final int LINE_COUNT = 5;
    private static final int POINT_COUNT = 100;

    private String currentCode;
    private Random random;

    public CaptchaGenerator() {
        random = new Random();
    }

    public Bitmap generateCaptcha() {
        // 创建位图
        Bitmap bitmap = Bitmap.createBitmap(WIDTH, HEIGHT, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);

        // 设置背景色
        canvas.drawColor(Color.WHITE);

        // 生成随机验证码
        StringBuilder codeBuilder = new StringBuilder();
        for (int i = 0; i < CODE_LENGTH; i++) {
            codeBuilder.append(CHARS.charAt(random.nextInt(CHARS.length())));
        }
        currentCode = codeBuilder.toString();

        // 绘制文字
        Paint paint = new Paint();
        paint.setTypeface(Typeface.DEFAULT_BOLD);
        paint.setTextSize(FONT_SIZE);
        paint.setAntiAlias(true);

        // 计算文字位置
        Rect bounds = new Rect();
        paint.getTextBounds(currentCode, 0, currentCode.length(), bounds);
        float x = (WIDTH - bounds.width()) / 2f;
        float y = (HEIGHT + bounds.height()) / 2f;

        // 绘制每个字符
        for (int i = 0; i < currentCode.length(); i++) {
            paint.setColor(getRandomColor());
            canvas.drawText(String.valueOf(currentCode.charAt(i)), x + i * (WIDTH / CODE_LENGTH), y, paint);
        }

        // 绘制干扰线
        for (int i = 0; i < LINE_COUNT; i++) {
            paint.setColor(getRandomColor());
            paint.setStrokeWidth(2);
            canvas.drawLine(
                    random.nextInt(WIDTH),
                    random.nextInt(HEIGHT),
                    random.nextInt(WIDTH),
                    random.nextInt(HEIGHT),
                    paint
            );
        }

        // 绘制干扰点
        for (int i = 0; i < POINT_COUNT; i++) {
            paint.setColor(getRandomColor());
            canvas.drawPoint(random.nextInt(WIDTH), random.nextInt(HEIGHT), paint);
        }

        return bitmap;
    }

    public String getCurrentCode() {
        return currentCode;
    }

    private int getRandomColor() {
        return Color.rgb(
                random.nextInt(150),
                random.nextInt(150),
                random.nextInt(150)
        );
    }
}